<?php

namespace App\Repositories\Eloquent\Admin;

use App\Repositories\Eloquent\BaseModel;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\AbstractModel;


class SysNodeModel extends AbstractModel
{
    use BaseModel;
    protected $tableName = 'k_sys_nodes';
    protected $connectionName = 'wr';
    protected $autoTimeStamp = true;
    protected $createTime = 'add_time';
    protected $updateTime = 'update_time';


    public function getList($where,$pageNum = 10) {
        $field = 'id,name,level,no,pid,path,module,controller,method,action,url,isaction,islogin,status,px,add_time,update_time';
        $list = $this->where($where)->field($field)->order('no,px', 'asc')->_page($pageNum);
        return $list;
    }


    public function getItemByUrl(string $url = ''){
         return $this->create()->get(['url'=>$url]);
    }

    public function getAllForList(array $datas = [])
    {
        $data = [];
        $field = ['id','name','level','no','pid','path','module','controller','method','class','action','url','isaction','islogin','status'];
        $list = $this->create()->field($field)->order('level,px','ASC')->all(function(QueryBuilder $queryBuilder)use($datas){
            $queryBuilder->where('status',1);
            $queryBuilder->where('deleted',0);
            $queryBuilder->where('level',3,'<');
            $queryBuilder->where('id',$datas,'in');
        });
        foreach($list as $item){
            $data[] = $item->toArray();
        }
        return $data;
    }

    public function getNodes($pid = 0,$datas=[],$data = []){
        $field = ['id','name','level','no','pid','path'];
        $list = $this->create()->field($field)->order('id','ASC')->all(function(QueryBuilder $queryBuilder)use($pid){
            $queryBuilder->where('status',1);
            $queryBuilder->where('deleted',0);
            $queryBuilder->where('pid',$pid);
        });
        $nodeDatas = [];
        foreach($list as $item){
            $item->toArray();
            $item['label'] = $item['name'];
            $nodeDatas[] = $item;
        }

        foreach ($nodeDatas as &$e) {

            if (in_array($e['id'], $datas) && $e['level'] > 0) {
                $e['checked'] = 'checked';
            }
            if (!empty($this->create()->where(['pid' => $e['id']])->get())) {
                $e['children'] = $this->getNodes($e['id'], $datas, $e);
            }
            unset($e['pid']);

        }

        return $nodeDatas;


    }



}